<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" size="small" label-width="68px">
            <el-form-item label="代理" prop="agentName">
                <el-input v-model="queryParams.agentName" placeholder="代理" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="账户名称" prop="accountName">
                <el-input v-model="queryParams.accountName" placeholder="账户名称" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="账户id" prop="accountId">
                <el-input v-model="queryParams.accountId" placeholder="账户id" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="渠道" prop="channel">
                <el-select v-model="queryParams.channel" placeholder="渠道" clearable>
                    <el-option v-for="dict in dict.type.sys_channel" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="渠道类型" prop="channelType">
                <el-select v-model="queryParams.channelType" placeholder="渠道类型" clearable>
                    <el-option v-for="dict in channelTypeList" :key="dict.value" :label="dict.name"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="账户类型" prop="accountType">
                <el-select v-model="queryParams.accountType" placeholder="账户类型" clearable>
                    <el-option v-for="dict in accountTypeList" :key="dict.value" :label="dict.name"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="应用" prop="pkg">
                <el-select v-model="queryParams.pkg" placeholder="应用" filterable>
                    <el-option v-for="(item, index) in productList" :key="item + index" :label="item.name"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['launch:account:add']">新增</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange" @cell-dblclick="_cellDblclick">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="账户id" align="center" prop="accountId" />
            <el-table-column label="账户名称" align="center" prop="accountName" />
            <el-table-column label="账户类型" align="center" prop="accountTypeName" />
            <el-table-column label="代理" align="center" prop="agentCode" >
              <template #default="scope">
                <dict-tag :options="dict.type.ACCOUNT_AGENT" :value="scope.row['agentCode']"/>
              </template>
            </el-table-column>
            <el-table-column label="渠道" align="center" prop="channel" >
              <template #default="scope">
                <dict-tag :options="dict.type.sys_channel" :value="scope.row['channel']"/>
              </template>
            </el-table-column>
            <el-table-column label="渠道类型" align="center" prop="channelTypeName" />
            <el-table-column label="主体" align="center" prop="channelTypeName" />
            <el-table-column label="appid" align="center" prop="appId" />
            <el-table-column label="secretKey" align="center" prop="secretKey" />
            <el-table-column label="accessToken" align="center" prop="accessToken">
                <template slot-scope="scope">
                    <span>{{ scope.row['accessToken'] && scope.row['accessToken'].substr(0, 10) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="refreshToken" align="center" prop="refreshToken">
                <template slot-scope="scope">
                    <span>{{ scope.row['refreshToken'] && scope.row['refreshToken'].substr(0, 10) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button v-if="scope.row.channel!=='oppo'" size="mini" type="text" icon="el-icon-edit" @click="getAuthorizeUrl(scope.row)">获取授权链接</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['launch:account:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:post:remove']">删除</el-button>
                    <el-button size="mini" type="text" icon="el-icon-document-copy" @click="handleCopy(scope.row)"
                        v-hasPermi="['launch:account:add']">复制账户</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改账户对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px" class="dialog-form">
                <el-form-item label="账户userid" prop="accountId">
                    <el-input v-model="form.accountId" placeholder="请输入账户id" />
                </el-form-item>
                <el-form-item label="账户名称" prop="accountName">
                    <el-input v-model="form.accountName" placeholder="请输入账户名称" />
                </el-form-item>
                <el-form-item label="代理" prop="agentCode">
                    <el-select v-model="form.agentCode" placeholder="代理" clearable size="small">
                        <el-option v-for="dict in dict.type.ACCOUNT_AGENT" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="渠道" prop="channel">
                    <el-select v-model="form.channel" placeholder="渠道" clearable size="small">
                        <el-option v-for="dict in dict.type.sys_channel" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="渠道类型" prop="channelType">
                    <el-select v-model="form.channelType" placeholder="渠道类型" clearable size="small">
                        <el-option v-for="dict in channelTypeList" :key="dict.value" :label="dict.name"
                        :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="账户类型" prop="accountType">
                    <el-select v-model="form.accountType" placeholder="账户类型" clearable size="small">
                        <el-option v-for="dict in accountTypeList" :key="dict.value" :label="dict.name"
                        :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="应用" prop="pkg">
                    <el-select v-model="form.pkg" placeholder="应用" filterable>
                        <el-option v-for="(item, index) in productList" :key="item + index" :label="item.name"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="主体名称" prop="mainBody">
                    <el-input v-model="form.mainBody" placeholder="请输入主体名称" />
                </el-form-item>
                <el-form-item label="appid" prop="appId">
                    <el-input v-model="form.appId" placeholder="请输入appid" />
                </el-form-item>
                <el-form-item label="secretKey" prop="secretKey">
                    <el-input v-model="form.secretKey" placeholder="请输入secretKey" />
                </el-form-item>
                <el-form-item label="accessToken" prop="accessToken">
                    <el-input v-model="form.accessToken" placeholder="请输入accessToken" />
                </el-form-item>
                <el-form-item label="refreshToken" prop="refreshToken">
                    <el-input v-model="form.refreshToken" placeholder="请输入refreshToken" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import baseTableAdv from '@/mixins/baseTableAdv';
import { objectToArrray, arrParamToStr, formatTime } from '@/utils/index';
import { listTable, getDetail, addItem, updateItem, delItem } from "@/api/place-manage/account";
import { getAllAgent } from "@/api/place-manage/agent";
import copy from 'clipboard-copy'

const channelType = { 1: '商店', 2: '非商店', 3: '信息流', 4: '搜索' }
const accountType = { 1: '管家账户', 2: '子账户' }
const statusType = { 0: '正常', 1: '停用' }

export default {
    name: "PlaceAccount",
    mixins: [baseTableAdv],
    dicts: ['sys_channel', 'ACCOUNT_AGENT'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 导出遮罩层
            exportLoading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 账户表格数据
            postList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                agentName: null,
                accountName: null,
                accountId: null,
                channel: null,
                channelType: null,
                accountType: null,
                pkg: null,
            },
            channelType: channelType,
            accountType: accountType,
            statusType: statusType,
            channelTypeList: objectToArrray(channelType),
            accountTypeList: objectToArrray(accountType),
            statusTypeList: objectToArrray(statusType),
            // 表单参数
            form: {
                accountId: '',
                accountName: '',
                agentCode: '',
                channel: '',
                channelType: '',
                accountType: '',
                pkg: '',
                mainBody: '',
                appId: '',
                secretKey: '',
                refreshToken: '',
                accessToken: ''
            },
            // 表单校验
            rules: {
                accountId: [
                    { required: true, message: "账户id不能为空", trigger: "blur" }
                ]
            }
        };
    },
    created() {
        this._getProductList();
        this.getList();
    },
    methods: {
        getAuthorizeUrl(row){
          let url = '';
          if(row.channel === 'huawei'){
            url = 'https://oauth-login.cloud.huawei.com/oauth2/v2/authorize?response_type=code&client_id='+row.appId+'&scope=https://www.huawei.com/auth/account/base.profile https://ads.cloud.huawei.com/report https://ads.cloud.huawei.com/promotion https://ads.cloud.huawei.com/tools https://ads.cloud.huawei.com/account https://ads.cloud.huawei.com/finance&access_type=offline&redirect_uri=http://476815xc06.qicp.vip/launch/account/huawei/callback&state='+row.id;
            // url = 'https://oauth-login.cloud.huawei.com/oauth2/v2/authorize?response_type=code&client_id='+row.appId+'&scope=https://www.huawei.com/auth/account/base.profile https://ads.cloud.huawei.com/report https://ads.cloud.huawei.com/promotion https://ads.cloud.huawei.com/tools https://ads.cloud.huawei.com/account https://ads.cloud.huawei.com/finance&access_type=offline&redirect_uri=https://tools.hnyynet.com.cn/ruoyi-admin/launch/account/huawei/callback&state='+row.id;
          }else if(row.channel === 'baidu'){
            url = 'https://u.baidu.com/oauth/page/index?platformId=4960345965958561794&appId='+row.appId+'&scope=1007690&state='+row.id+'&callback=https://tools.hnyynet.com.cn/ruoyi-admin/launch/account/baidu/callback';
          }else if(row.channel === 'vivo'){
            url = 'https://open-ad.vivo.com.cn/OAuth?clientId='+row.appId+'&state='+row.id+'&redirectUri=https://tools.hnyynet.com.cn/ruoyi-admin/launch/account/vivo/callback';
            // url = 'https://open-ad.vivo.com.cn/OAuth?clientId='+row.appId+'&state='+row.id+'&redirectUri=https://476c81m506.wocp.fun/launch/account/vivo/callback';
          }else if(row.channel === 'yingyongbao'){
            url = 'https://developers.e.qq.com/oauth/authorize?client_id='+row.secretKey+'&state='+row.id+'&redirect_uri=https://developers.e.qq.com/app/manage/'+row.secretKey;
          }
          if(url){
            copy(url)
            this.$modal.msgSuccess('授权链接已复制到剪贴板');
          }else{
            this.$modal.msgError('没有该渠道的授权链接');
          }
        },
        _cellDblclick(row, column, cell, event) {
            if (!['refreshToken', 'accessToken', 'secretKey', 'appId'].includes(column.property)) return
            copy(row[column.property])
            this.$modal.msgSuccess('数据已复制到剪贴板');
        },
        /** 查询账户列表 */
        getList() {
            this.loading = true;
            listTable(this.queryParams).then(response => {
                this.postList = response.rows.map(item => {
                    item.accountTypeName = accountType[item.accountType];
                    item.channelTypeName = channelType[item.channelType];
                    return item;
                });
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                accountId: '',
                accountName: '',
                agentCode: '',
                channel: '',
                channelType: '',
                accountType: '',
                pkg: '',
                mainBody: '',
                appId: '',
                secretKey: '',
                refreshToken: '',
                accessToken: ''
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.postId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加账户";
        },
        /** 复制按钮操作 */
        handleCopy(row) {
            this.reset();
            // 复制行数据到表单，排除不应复制的字段
            Object.keys(this.form).forEach(key => {
              this.form[key] = row[key];
            });
            // 清空账户ID和账户名称，让用户重新输入
            this.form.accountId = '';
            // this.form.accountName = '';
            this.open = true;
            this.title = "复制添加账户";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const rowId = row.id || this.ids
            getDetail(rowId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改账户";
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != undefined) {
                        updateItem(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addItem(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const postIds = row.id || this.ids;
            this.$modal.confirm('是否确认删除账户编号为"' + postIds + '"的数据项？').then(function () {
                return delItem(postIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
    }
};
</script>

<style lang="scss" scoped>
.dialog-form {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .el-form-item {
        width: 46%;
        .el-select {
            width: 100%;
        }
    }
}
</style>
